package com.xgr.wonderful.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.base.BasePageActivity;
import com.xgr.wonderful.adapter.CommentAdapter;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.entity.Comment;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LocationUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.ToastFactory;

/**
 * 评论考虑直接 推送整个status过去 
 * @author lsj
 *
 */
public class CommentActivity extends BasePageActivity{
	
	private ActionBar mActionBar ;
	
	private EditText mCommentContent ;
	private Button mCommit ;
	
	private ArrayList<Comment> mListItems ;
	private Status mStatus = null ;
	private CommentAdapter commentAdapter ;
	private PullToRefreshListView mPullToRefreshListView ;
	private ListView actualListView ;
	
	private  enum RefreshType {
		REFRESH , LOAD_MORE 
	};

	private RefreshType mRefreshType = RefreshType.REFRESH ;
	
	private Integer latestCommentId =0;
	private User mUser ;  //本地用户
	private User toUser  ;//评论别人的回复
	
	private HttpProxy httpProxy ; 
	
	private int clickIndex = -1 ;
	
	private boolean commentToComment = false ;
	
	@Override
	protected void setLayoutView() {
		setContentView(R.layout.activity_comment) ;
	}

	@Override
	protected void findViews() {
		mActionBar = (ActionBar)findViewById(R.id.actionbar_comment) ;
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.comment_pull_list) ;
		mCommentContent = (EditText)findViewById(R.id.comment_content) ;
		mCommit = (Button)findViewById(R.id.comment_commit) ;
	}

	@Override
	protected void setupViews(Bundle bundle) {
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
						| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		
		mActionBar.setTitle("评论") ;
		mActionBar.setDisplayHomeAsUpEnabled(true) ;
		mActionBar.setHomeAction(new Action() {
			@Override
			public void performAction(View view) {
//				Intent resIntent = new Intent();
//				resIntent.putExtra(Constant.COMMENT_NUM_INCREAMENT, comment_times);
//				setResult(RESULT_OK, resIntent);
				finish() ; // not ok 
			}
			@Override
			public int getDrawable() {
				return R.drawable.weix_logo_blank;
			}
		}) ;
		mUser = LocalUserUtils.getInstance().getLocalUser();
		httpProxy = new HttpProxy() ;
		
		//这个是自己点击 进行的情况
		mStatus = (Status)getIntent().getSerializableExtra("data") ;

		mPullToRefreshListView.setMode(Mode.PULL_FROM_END) ;
		//设置上下拉时的显示文字 ,还可以设置图片
		ILoadingLayout startLabels = mPullToRefreshListView
				.getLoadingLayoutProxy(true, false);
		startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
		startLabels.setRefreshingLabel("正在载入...");// 刷新时
		startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

		ILoadingLayout endLabels = mPullToRefreshListView
				.getLoadingLayoutProxy(false, true);
		endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
		endLabels.setRefreshingLabel("正在载入...");// 刷新时
		endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示
		
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				mPullToRefreshListView.setMode(Mode.PULL_FROM_END) ;
				mRefreshType = RefreshType.LOAD_MORE ;
				fetchData() ;
			}
		}) ;
		
		actualListView = mPullToRefreshListView.getRefreshableView() ;
		
		mListItems = new ArrayList<Comment>() ;
		commentAdapter = new CommentAdapter(mContext, mListItems, mStatus) ;
		actualListView.setAdapter(commentAdapter) ;
		if (mListItems == null || mListItems.size()==0){
			fetchData() ;
		}
		actualListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				LogUtils.i(TAG, "posidtion:"+ position) ;
				LogUtils.i(TAG, "mListItems size:"+ mListItems.size()) ;
				if (position==1) return ;
				clickIndex = position -2 ;
				//被回复的评论者
				toUser = mListItems.get(clickIndex).getUser() ;
				mCommentContent.setHint("回复"+toUser.getUsername()+":") ;
				mCommentContent.requestFocus() ;//得到focus 
				InputMethodManager imm = (InputMethodManager)
						getSystemService(Context.INPUT_METHOD_SERVICE) ;
				imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED) ; //强制弹出键盘
				
				commentToComment = true ; //说明 是在回复 别人的评论

			}
		}) ;
		
		actualListView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				LogUtils.i(TAG, "onScrollStateChanged") ;
				commentToComment = false ;
				mCommentContent.setHint("来评论一句吧") ;
				hideSoftInput() ;
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		}) ;
		
	}

	@Override
	protected void setListener() {
		//如果之前点击的是回复别人的评论，然后又不想回复了，点击外面就可以了。
		
		mCommit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String content = mCommentContent.getText().toString().trim() ;
				if (content == null || content.length() ==0){
					ToastFactory.getToast(mContext, "请输入内容").show() ;
					return ;
				}
				if (commentToComment== true&& toUser!= null && toUser.getID()!= null){
					//评论别人的回复
					content = "回复"+ toUser.getUsername()+":"+content;  
					publishComment(content, latestCommentId, toUser.getID(), toUser.getUsername()) ;
				}else {
					//直接评论的状态
					publishComment(content, latestCommentId, null , null) ;
				}
			}
		}) ;
	}

	private  void fetchData() {
		if (mStatus== null) return ; //以防万一，可以不要
		Comment comment = new Comment(mStatus.getId(), 
				latestCommentId, Constant.NUMBERS_PER_PAGE) ;
		String commentJson = new Gson().toJson(comment) ;
		
		httpProxy.queryComment(commentJson, new IHttpRequestListener() {
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				List<Comment> queryList = null ;
				if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
					queryList = new Gson().fromJson(result, 
							new TypeToken<List<Comment>>() {
					}.getType()) ;
					if (queryList != null && queryList.size()!= 0){
						if (queryList.size()< Constant.NUMBERS_PER_PAGE){
							ToastFactory.getToast(mContext, "没有更多评论了").show() ;
						}
						mListItems.addAll(queryList) ;
						latestCommentId = mListItems.get(mListItems.size()-1 ).getId();
						commentAdapter.notifyDataSetChanged() ;
					}else if (queryList!= null && queryList.size() ==0) {
						if (latestCommentId > 0){
							//说明 有评论且不是第一次拉取，然后没有数据了
							ToastFactory.getToast(mContext, "没有更多评论了").show() ;
						}else {
							//本来就没有评论，所以为0， 不用显示
							ToastFactory.getToast(mContext, "暂时还没有评论").show() ;
						}
					}
					setState(LOADING_COMPLETE) ;
					mPullToRefreshListView.onRefreshComplete() ;
				}else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
					ToastFactory.getToast(mContext, "加载数据失败").show();
					setState(LOADING_FAILED) ;
					mPullToRefreshListView.onRefreshComplete() ;
				}
			}
			
			@Override
			public void OnHttpRequestStart() {
				LogUtils.i(TAG, "开始查询") ;
				setState(LOADING) ;
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				ToastFactory.getToast(mContext, "加载数据失败").show();
				setState(LOADING_FAILED) ;
				mPullToRefreshListView.onRefreshComplete() ;
			}
		}) ;
	}
	/**
	 * 发表，发表后只是收起键盘，不进行别的处理，只有拉取后才能看到已经发表的评论。
	 * 且发表后mStatus显示的 评论数不变化 
	 * @param content
	 * @param latest 当前已经加载的最新评论id，默认为0。用于返回未加载的新评论，意义不明
	 * @param toid  表示这条评论是回复 id的回复 ， 可以不填(暂时为null)
	 * @param toUsername 当回复是别人的评论的时候，要加入到content中去，别的时候不要
	 */
	private void publishComment(String content , Integer latest, Integer toid, String toUsername ){

		Comment comment = new Comment(mStatus.getId(), mUser.getID(),
				toid, content,
				sputil.getLatestLocation().getLatitude(),
				//LocationUtils.getInstance().getLatitude(),
				sputil.getLatestLocation().getLongtitude(),
				//LocationUtils.getInstance().getLongtitude(),
				latest) ;
		String commentJson = new Gson().toJson(comment) ;
		
		httpProxy.publishComment(commentJson, new IHttpRequestListener() {
			
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
					ToastFactory.getToast(mContext, "发表评论成功").show();
					mCommentContent.setText("") ;//清空输入内容 
					Status pushStatus = new Status(null, mStatus.getId());
					if (commentToComment== true){
						//回复别人的评论
						notifyPeer(String.valueOf(toUser.getID()),
								mUser.getUsername(), pushStatus) ;
					}else {
						//回复的状态 
						notifyPeer(String.valueOf(mStatus.getUser().getID()),
								mUser.getUsername(), pushStatus) ;
					}
					refresh() ; //在一定情况 下直接显示出新的评论
					hideSoftInput() ;
				}else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
					ToastFactory.getToast(mContext, "发表评论失败").show() ;
				}
			}
			
			@Override
			public void OnHttpRequestStart() {
				ToastFactory.getToast(mContext, "正在发表评论").show() ;
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				ToastFactory.getToast(mContext, "发表失败").show();
			}
		}) ;
	}
	
	/**
	 * 在一定条件下，评论后直接再次refresh
	 */
	public void refresh() {
		//如果目前已经有的状态数不够一次拉取的，则loadmore一次
		if (mListItems.size()<=Constant.NUMBERS_PER_PAGE){
			mRefreshType = RefreshType.LOAD_MORE; 
			fetchData() ;
		}
		int count = actualListView.getCount();
		if (count > 0) {
			actualListView.setSelection(count - 1);
		}
	}
	
	private static final int LOADING = 1;
	private static final int LOADING_COMPLETE = 2;
	private static final int LOADING_FAILED = 3;
	private static final int LOADING_NO_MORE = 4;
	
	/**
	 * 不用进行什么动作
	 * @param state
	 */
	private void setState(int state ){
		switch (state) {
		case LOADING:
			LogUtils.i(TAG, "state:LOADING") ;
			break;
		case LOADING_COMPLETE:
			LogUtils.i(TAG, "state:LOADING_COMPLETE") ;
			break ;
		case LOADING_FAILED:
			LogUtils.i(TAG, "state:LOADING_FAILED") ;
			break ;
		case LOADING_NO_MORE:
			LogUtils.i(TAG, "state:LOADING_NO_MORE") ;
			break ;
		default:
			break;
		}
	}
	
	/**
	 * 在发表一次成功后，收起键盘
	 */
	private void hideSoftInput (){
		InputMethodManager imm = (InputMethodManager)
				getSystemService(Context.INPUT_METHOD_SERVICE) ;
		imm.hideSoftInputFromWindow(mCommentContent.getWindowToken(), 0) ;
	}
	
	/**
	 * 测试的时候 ，可以先让自己也收到消息
	 * 与remoteUserId建立起对话，将mStatus作为 txt发送过去
	 * 但是只发送了statusid，对方在收到后再从服务器摘取数据 
	 * COMMENT_PUSH_BY_HX,消息的接收方是remoteUserId 
	 * @param remoteUserId 被评论的用户id 
	 * @param pushStatus  这条状态 
	 * @param fromUsername  评论者的用户名
	 */
	private void notifyPeer(String remoteUserId, String fromUsername,Status pushStatus ){
		if (remoteUserId.equals(mUser.getID().toString())){
			LogUtils.i(TAG, "comment to yourself") ;
			LogUtils.i(TAG, "remoteUserId:"+ remoteUserId+ "localuserid:"+ mUser.getID()) ;
			return  ;//评论的自己发表的状态 
		}
		LogUtils.i(TAG, "comment to remote:"+ remoteUserId) ;
		String pushStatusJson = new Gson().toJson(pushStatus) ;
		final EMConversation emConversation = EMChatManager.getInstance()
				.getConversation(remoteUserId) ;
		final EMMessage msg = EMMessage.createSendMessage(EMMessage.Type.TXT) ;
		TextMessageBody txtBody = new TextMessageBody(pushStatusJson) ;
		msg.setAttribute(Constant.COMMENT_PUSH_BY_HX, true) ;
		msg.setAttribute(Constant.COMMENT_PUSH_FROM, fromUsername) ;
		msg.addBody(txtBody) ;
		msg.setReceipt(remoteUserId) ;
		emConversation.addMessage(msg) ;
		EMChatManager.getInstance().sendMessage(msg, new EMCallBack() {
			
			@Override
			public void onSuccess() {
				LogUtils.i(TAG, "msg send success") ;
				emConversation.removeMessage(msg.getMsgId()) ;//一定要有，评论成功，进行删除 
			}
			
			@Override
			public void onProgress(int arg0, String arg1) {
				LogUtils.i(TAG, "msg send ing") ;
			}
			
			@Override
			public void onError(int code, String error) {
				LogUtils.i(TAG, "msg send error:"+ code+ error) ;
			}
		}) ;
		
	}


}
